//
//  MainViewController.m
//  Alltelevisionnews
//
//  Created by dllo on 15/11/26.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "MainViewController.h"
#import "ZDQMainTableView.h"
#import <MessageUI/MFMessageComposeViewController.h>
#import "ZDQMainSendViewController.h"
#import "ZDQAboutMainViewController.h"

@interface MainViewController ()<MFMessageComposeViewControllerDelegate, ZDQMainTableViewDelegate>

@property(nonatomic, strong) UIView *changView;
@property(nonatomic, strong) UIPickerView *pickerView;
@property(nonatomic, strong) NSArray *month;
@property(nonatomic, strong) NSArray *day;
@property(nonatomic, strong) NSString *hours;
@property(nonatomic, strong) NSString *minutes;
@property(nonatomic, strong) UILabel *timeLabel;
@property(nonatomic, strong) UIButton *timeButton;
@property(nonatomic, assign) NSInteger clickCount;
@property(nonatomic, strong) UIButton *nightButton;
 
@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    
    
    UIButton *menuBtu = [UIButton buttonWithType:UIButtonTypeCustom];
    menuBtu.frame = CGRectMake(0, 0, 20, 18);
    [menuBtu setBackgroundImage:[UIImage imageNamed:@"menu"] forState:UIControlStateNormal];
    [menuBtu addTarget:self action:@selector(openOrCloseLeftList) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:menuBtu];
    
    self.nightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nightButton.frame = CGRectMake(0, 0, 30, 30);
    [self.nightButton setBackgroundImage:[UIImage imageNamed:@"night.png"] forState:UIControlStateNormal];
    [self.nightButton addTarget:self action:@selector(nightButton:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.nightButton];
    
    NSString *sandBox = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *docPath = [sandBox stringByAppendingPathComponent:@"button.plist"];
    
    NSString *Str = [NSKeyedUnarchiver unarchiveObjectWithFile:docPath];
    
    if ([Str isEqualToString:@"确认"]) {
        [self.nightButton setBackgroundImage:[UIImage imageNamed:@"day.png"] forState:UIControlStateNormal];
        self.clickCount = 0;
        
    } else {
        
        [self.nightButton setBackgroundImage:[UIImage imageNamed:@"night.png"] forState:UIControlStateNormal];
        self.clickCount = 1;
    }

    
    if ([ZDQSingleton shareSingleton].isLongin == YES) {
        self.view.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.3 alpha:1];
        
    } else {
        
        self.view.backgroundColor = [UIColor whiteColor];
        
    }

    
    
    ZDQMainTableView *main = [[ZDQMainTableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    [self.view addSubview:main];
    main.backgroundColor = [UIColor clearColor];
    main.tag = 10000;
    [main mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(self.view).with.offset(0);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.bottom.equalTo(self.view).with.offset(0);
        
    }];
    main.dataSource = main;
    main.delegate = main;
    main.iddelegate = self;
    
//    self.month = [NSArray arrayWithObjects:@"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10", @"11", @"12", @"13", @"14", @"15", @"16", @"17", @"18", @"19", @"20", @"21", @"22", @"23", nil];
//    self.day = [NSArray arrayWithObjects:@"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10", @"11", @"12", @"13", @"14", @"15", @"16", @"17", @"18", @"19", @"20", @"21", @"22", @"23", @"24", @"25", @"26", @"27", @"28", @"29", @"30",@"31", @"32", @"33", @"34", @"35", @"36", @"37", @"38", @"39", @"40", @"41", @"42", @"43", @"44", @"45", @"46", @"47", @"48", @"49", @"50", @"51", @"52", @"53", @"54", @"55", @"56", @"57", @"58", @"59", nil];
//    
//    self.changView = [[UIView alloc] init];
//    [self.view addSubview:self.changView];
//    self.changView.backgroundColor = [UIColor whiteColor];
//    [self.changView mas_makeConstraints:^(MASConstraintMaker *make) {
//       
//        make.top.equalTo(self.view).with.offset(KHEIGHT / 2 + 50 * KHEIGHT / 667);
//        make.left.equalTo(self.view).with.offset(10);
//        make.right.equalTo(self.view).with.offset(-10);
//        make.bottom.equalTo(self.view).with.offset(-10);
//        
//    }];
//    
//    self.pickerView = [[UIPickerView alloc] init];
//    [self.changView addSubview:self.pickerView];
//    [self.pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.top.equalTo(self.changView).with.offset(20);
//        make.left.equalTo(self.changView).with.offset(100);
//        make.right.equalTo(self.changView).with.offset(-100);
//        make.bottom.equalTo(self.changView).with.offset(-40);
//        
//    }];
//    self.pickerView.dataSource = self;
//    self.pickerView.delegate = self;
//    
//    self.timeLabel = [[UILabel alloc] init];
//    [self.changView addSubview:self.timeLabel];
//    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.top.equalTo(self.changView).with.offset(0);
//        make.left.equalTo(self.changView).with.offset(120);
//        make.right.equalTo(self.changView).with.offset(-110);
//        make.bottom.equalTo(self.pickerView.mas_top).with.offset(0);
//    }];
//    
//    //            self.timeLabel.layer.borderWidth = 1;
//    self.timeLabel.textAlignment = NSTextAlignmentCenter;
//    self.timeLabel.text = @"0时0分";
//    
//    self.timeButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    [self.changView addSubview:self.timeButton];
//    [self.timeButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.top.equalTo(self.pickerView.mas_bottom).with.offset(-0);
//        make.left.equalTo(self.changView).with.offset(120);
//        make.right.equalTo(self.changView).with.offset(-110);
//        make.bottom.equalTo(self.changView).with.offset(-10);
//        
//    }];
//    
//    [self.timeButton setTitle:@"确认提醒" forState:UIControlStateNormal];
//    [self.timeButton addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
//    self.changView.hidden = YES;
//    
//    void(^block)(BOOL) = ^(BOOL switchon) {
//        
//        if (switchon == 1) {
//          
//            self.changView.hidden = NO;
//            
//        } else {
//            
//            self.changView.hidden = YES;
//            
//        }
//    };
//    main.block = block;
//    
    
}



#pragma mark tableView的协议方法

- (void)clicktableViewcell:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        collectViewController *colletVC = [[collectViewController alloc] init];
        [self.navigationController pushViewController:colletVC animated:YES];
    }
    if (indexPath.section == 1) {
        
        if (indexPath.row == 0) {

            [self sendSMS:@"" recipientList:@[@"18642222320"]];
            
        } else if (indexPath.row == 1) {
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://18642222320"]];
        
        } else {
            
            ZDQMainSendViewController *SendVC = [[ZDQMainSendViewController alloc] init];
            [self.navigationController pushViewController:SendVC animated:YES];
        }
    } else if (indexPath.section == 3) {
       
        ZDQAboutMainViewController *aboutVC = [[ZDQAboutMainViewController alloc] init];
        [self.navigationController pushViewController:aboutVC animated:YES];
    }
    if (indexPath.section == 2) {
        
        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSFileManager *manager = [NSFileManager defaultManager];
        CGFloat cachesSize = [self folderSizeAtPath:cachePath];
        BOOL result = [manager removeItemAtPath:cachePath error:nil];
        if (result) {
            UIAlertController *aleryController = [UIAlertController alertControllerWithTitle:@"清除缓存" message:[NSString stringWithFormat:@"%@%.2fM", @"清除", cachesSize] preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:aleryController animated:YES completion:nil];
            UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
            [aleryController addAction:leftAction];
        } else {
         
            NSLog(@"删除失败");
            
        }
        
        if (cachesSize == 0) {
            UIAlertController *aleryController = [UIAlertController alertControllerWithTitle:@"清除缓存" message:@"缓存已经清空" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:aleryController animated:YES completion:nil];
            UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *rightAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
            [aleryController addAction:leftAction];
            [aleryController addAction:rightAction];

        }
        
        ZDQMainTableView *tableView = (ZDQMainTableView *)[self.view viewWithTag:10000];
        NSString *acachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSLog(@"*******************%@", acachePath);
        tableView.cachesSize  = [self folderSizeAtPath:acachePath];
        [tableView reloadData];
        
    }

}

- (float)folderSizeAtPath:(NSString *)folderPath {
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return  0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString *fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil) {
        NSString *fileAbsoltePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsoltePath];
    }
    return folderSize / (1024.0 *1024.0);
}

- (long long)fileSizeAtPath:(NSString *)filePath {
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]) {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}


#pragma mark夜间模式的方法
- (void)nightButton:(UIButton *)button {
    
    if (self.clickCount % 2 != 0) {
        
        NSString *sandBox = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *docPath = [sandBox stringByAppendingPathComponent:@"button.plist"];
        [NSKeyedArchiver archiveRootObject:@"确认" toFile:docPath];
        NSLog(@"%@", docPath);
        [self.nightButton setBackgroundImage:[UIImage imageNamed:@"day.png"] forState:UIControlStateNormal];
        [ZDQSingleton shareSingleton].isLongin = YES;
        ZDQMainTableView *main = (ZDQMainTableView *)[self.view viewWithTag:10000];
        self.view.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.3 alpha:1];
        [main reloadData];
        
    } else {
        
        NSString *sandBox = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *docPath = [sandBox stringByAppendingPathComponent:@"button.plist"];
        [NSKeyedArchiver archiveRootObject:@"取消" toFile:docPath];
        [self.nightButton setBackgroundImage:[UIImage imageNamed:@"night.png"] forState:UIControlStateNormal];
        [ZDQSingleton shareSingleton].isLongin = NO;
        ZDQMainTableView *main = (ZDQMainTableView *)[self.view viewWithTag:10000];
        self.view.backgroundColor = [UIColor whiteColor];
        [main reloadData];
    }
    
    self.clickCount++;
    
}


#pragma mark 下面四个button的点击方法
- (void)buttonAction:(UIButton *)button
{
    
    if (button.tag == 1000) {
        
        UILabel *nightLabel = (UILabel *)[self.changView viewWithTag:2000];
        if ([nightLabel.text isEqualToString:@"夜间模式"]) {
            [button setImage:[UIImage imageNamed:@"day.png"] forState:UIControlStateNormal];
            nightLabel.text = @"日间模式";
        }  else {
            
            [button setImage:[UIImage imageNamed:@"night.png"] forState:UIControlStateNormal];
            nightLabel.text = @"夜间模式";
            
        }
    }
}

- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    
    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
    
    if([MFMessageComposeViewController canSendText])
        
    {
        // 方法携带的内容作为短信息内容
        controller.body = bodyOfMessage;
        // 方法携带的数组里的号码作为收信号码
        controller.recipients = recipients;
        // 代理人
        controller.messageComposeDelegate = self;
        // 模态到短信息视图
        [self presentViewController:controller animated:YES completion:^{
            
        }];
    }
}
// 处理发送完的响应结果
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{   // 返回之前视图
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    // 取消发送
    if (result == MessageComposeResultCancelled)
    {
        NSLog(@"Message cancelled");
    }
    // 已发送
    else if(result == MessageComposeResultSent)
    {
        NSLog(@"Message sent");
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"系统提示" message:@"已发送" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        
        [alertController addAction:alertAction];
        [self presentViewController:alertController animated:YES completion:^{
        }];
    }
    // 发送失败
    else
    {
        NSLog(@"Message failed");
    }
}




#pragma mark 抽屉的button的点击方法
- (void)openOrCloseLeftList {
    
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (tempAppDelegate.leftslideVC.closed) {
        
        [tempAppDelegate.leftslideVC openLeftView];
        
    } else {
        
        [tempAppDelegate.leftslideVC closeLeftView];
        
    }
    
}


- (void)viewWillAppear:(BOOL)animated {
    
    ZDQMainTableView *tableView = (ZDQMainTableView *)[self.view viewWithTag:10000];
    NSString *acachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    tableView.cachesSize  = [self folderSizeAtPath:acachePath];
    [tableView reloadData];
    
}



//#pragma mark 提醒的方法
//- (void)click:(UIButton *)button {
//
//    [[UIApplication sharedApplication] cancelAllLocalNotifications];
//    //一个本地推送
//    UILocalNotification *notification = [[UILocalNotification alloc] init];
//    if (notification != nil) {
//        if (self.hours.length == 0 || self.minutes.length == 0) {
//            notification.fireDate = [NSDate dateWithTimeIntervalSince1970:60 * 30];
//        }
//        else {
//            NSInteger h = self.hours.integerValue - 8;
//            if (h < 0) {
//                h += 24;
//            }
//            NSInteger m = self.minutes.integerValue;
//            notification.fireDate = [NSDate dateWithTimeIntervalSince1970:h * 60 * 60 + m * 60];
//        }
//        NSLog(@"%@", notification.fireDate);
//        // 设置时区
//        notification.timeZone = [NSTimeZone defaultTimeZone];
//        // 设置重复间隔
//        notification.repeatInterval = kCFCalendarUnitDay;
//        // 推送声音
//        notification.soundName = UILocalNotificationDefaultSoundName;
//        notification.soundName = @"Bell.caf";
//        // 推送内容
//        notification.alertBody = @"海量新闻更新,点击查看";
//        //显示在icon上的红色圈中的数子
//        notification.applicationIconBadgeNumber = 1;
//        //添加推送到UIApplication
//        UIApplication *app = [UIApplication sharedApplication];
//        [app scheduleLocalNotification:notification];
//        
//        if (self.hours.length == 0 && self.minutes.length == 0) {
//            self.hours = @"8";
//            self.minutes = @"30";
//        }
//        
//        NSString *informContent = [NSString stringWithFormat:@"下次提醒时间为%@时%@分", self.hours, self.minutes];
//        UIAlertController *AlertController = [UIAlertController alertControllerWithTitle:@"系统提示" message:informContent preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *Action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        }];
//        [AlertController addAction:Action];
//        [self presentViewController:AlertController animated:YES completion:^{
//        }];
//        
//    }
//}
//
//

//#pragma mark pickerView的协议方法
//- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
//    return 2;
//}
//
//// UIPickerViewDataSource协议中必须实现的方法 设置每列个数
//- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
//    if (component == 0) {
//        return self.month.count;
//    }
//    else {
//        return self.day.count;
//    }
//}
//
//// 设置每列宽度
//- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
//    
//    return 38;
//}
//
//// 返回选中的行
//- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
//{
//    if (component == 0) {
//        NSLog(@"%@", self.month[row]);
//        self.hours = self.month[row];
//    } else {
//        NSLog(@"%@", self.day[row]);
//        self.minutes = self.day[row];
//    }
//    
//    if (self.hours.length == 0) {
//        self.hours = @"0";
//    }
//    
//    if (self.minutes.length == 0) {
//        self.minutes = @"0";
//    }
//    
//     self.timeLabel.text = [NSString stringWithFormat:@"%@时%@分", self.hours, self.minutes];
//    
//    
//}
//
////返回当前行的内容,此处是将数组中数值添加到滚动的那个显示栏上
//-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
//{
//    if (component == 0) {
//        return [self.month objectAtIndex:row];
//    } else {
//        return [self.day objectAtIndex:row];
//        
//    }
//}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
